
#include "../include/core.h"
#include "../include/session.h"
#include "../include/connector.h"
#include "../include/mylog.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>

static int times = 0;
void handleConnection(struct session* session, void* privateData) {
	printf("onConnection\n");
	if (!session) {
		fprintf(stderr, "handle connecton error!!! session is null!!!!\n");
		return;
	}

	char sendBuf[1024 ];
	snprintf(sendBuf, sizeof(sendBuf) - 1, "client data, times is %d", ++times);
	int sendBufLen = strlen(sendBuf);

	int ret = writeSession(session, sendBuf, sendBufLen);
	printf("client send data: %s, ret: %d\n", sendBuf, ret);
}

RetHandle handleData(struct session* session, void* privateData) {
	printf("handleData\n");
	if (!session) {
		fprintf(stderr, "hanleData, session is null!!!\n");
		return -1;
	}

	int readBufLen = getReadableBytesBuffer(session->readBuffer);
	if (readBufLen <= 0) {
		mylog(LOG_INFO, "in handleData, no Data!!!");
		return 0;
	}

	if (readBufLen > 1024 * 100) {
		mylog(LOG_INFO, "read buffer too longer!!!");
		return -2;
	}

	char tmp[1024 * 100];
	memcpy(tmp, (void*)getReadIndexBuffer(session->readBuffer), readBufLen);
	int tmpLen = readBufLen;//strlen(tmp);
	moveReadIndexBuffer(session->readBuffer, readBufLen);

	//printf("%s", tmp);

	writeSession(session, tmp, tmpLen);
	return 0;
}

void handleDisConnection(struct session* session, void* privateData) {
	printf("onDisConnection\n");
}


struct core* c = NULL;
void onSigInt(int sig) {
	if (c) {
		mylog(LOG_INFO, "STOP CORE!!!");
		stopCore(c);
	}
}


int main(){

	signal(SIGINT, onSigInt);
	int workThreadNum = 0;
	c = initCore(workThreadNum, 0);
	if (!c) {
		printf("init core error!!\n");
		exit(-1);
	}

	char* serverAddr = "127.0.0.1";
	int serverPort = 1208;
	int i;
	//for (i = 0; i < 800; i++) {
	struct connector* con =
			initConnector(
					serverAddr,
					serverPort);

	if (!con) {
		fprintf(stderr, "new connector error!!!\n");
		destroyCore(c);
		exit(-2);
	}

	setRetryMs(con, 1000);
	con->callBackHandle->onConnectionCallBack = handleConnection;
	con->callBackHandle->onDataCallBack = handleData;
	con->callBackHandle->onDisConnectionCallBack = handleDisConnection;

	startNonBlockConnect(con, c);
	//mylog(LOG_INFO, "START CON ID[%d]", i);
	//}

	mylog(LOG_INFO, "startclient!!!\n");
	eventLoopCore(c );
	mylog(LOG_INFO, "endclient!!!!\n");

	destroyCore(c);
	destroyConnector(con);

	return 0;
}
